<template>
    <eui-background type="common">
        <eui-nav-bar title="拣货任务" color="#fff" />
        <view style="padding: 0 15rpx">
            <view class="flex">
                <eui-search-bar v-model="pickTaskNo" @confirm="searchConfirm" radius="100" leftIcon="icon-saoyisao"
                    placeholder="拣货任务单号" @clear="clearSearch('taskno')" @leftIconClick="scanCode('taskno')">
                </eui-search-bar>
                <eui-search-bar v-model="code" @confirm="changeGdsPickNum" radius="100" leftIcon="icon-saoyisao"
                    placeholder="商品编码/条码" @clear="clearSearch('goods')" @leftIconClick="scanCode('goods')">
                </eui-search-bar>
            </view>
        </view>
        <view class="footer" :style="{ height: height + 'px', 'overflow-y': 'scroll' }">
            <DetailPickTaskItem :scope="pickTaskDetail" />
            <Title :type="pickTaskDetail?.pickTaskStatus == '1' ? '拣货' : '合流'" />
            <scroll-view scroll-y="true" style="width: 100%;box-sizing: border-box;overflow-y: scroll;">
                <PickGoodsList :scope="pickTaskDetail" :goodsList="goodsList" @itemClick="itemClick" />
            </scroll-view>
        </view>
        <view class="bottom"
            v-if="(pickTaskDetail?.pickTaskStatus == '1') || (pickTaskDetail?.pickTaskStatus == '2' && pickTaskDetail.confluenceStatus != '1')">
            <eui-button type="primary" title="拣货完成" @click="pickingComplete" style="width: 220rpx;"
                v-if="pickTaskDetail?.pickTaskStatus == '1'" />
            <eui-button type="primary" title="合流完成" @click="mergeComplete" style="width: 220rpx;"
                v-if="pickTaskDetail?.pickTaskStatus == '2' && pickTaskDetail?.confluenceStatus != '1'" />
        </view>

        <eui-popup ref="pickTaskGdsPopup" background-color="#f1f1f1" type="bottom" :mask-click="false">
            <view class="popup-content">
                <view class="popup-title flex just-between">
                    <view style="font-weight: bold;">
                        拣货
                    </view>
                    <bcm-close-btn @click="closePickTaskGdsPopup" />
                </view>
                <view
                    style="padding-left: 30rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;font-size: 32rpx; line-height: 32rpx;height: 30vh;">
                    <eui-card-input type="text" v-model="currentItem.goodsNum" title="应拣数量" showBottomLine="false"
                        alignType="left" :showBottomLine="false" disabled />
                    <eui-card-input type="number" required v-model="currentItem.pickNum" title="实拣数量"
                        showBottomLine="false" alignType="left" />
                </view>
            </view>
            <view class="bottom-1">
                <eui-button type="max2" @buttonClick="closePickTaskGdsPopup" title="关闭" style="width: 40%;" />
                <eui-button @click="submit" title="确认" style="width: 40%;" type="max" />
            </view>
        </eui-popup>

    </eui-background>
</template>
<script setup lang="js">
import { ref, computed, onMounted } from 'vue'
import { onLoad, onShow } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import BcmCloseBtn from '../components/BcmCloseBtn'
import DetailPickTaskItem from './components/DetailPickTaskItem';
import PickGoodsList from './components/PickGoodsList';
import Title from './components/Title';

const bcmUrl = getBcmUrl()
const code = ref('')
const pickTaskNo = ref('')
const BillId = ref('')
const StoreCode = ref('')
const pickTaskDetail = ref()
const height = ref('')
const pickTaskGdsPopup = ref(false)
const goodsList = ref([])
const currentItem = ref(null)

const getData = async (id, storeCode) => {
    service.enjoyShowLoading('正在加载...')
    const param = {
        IsNotPage: true,
        QueryCountFlag: false,
        WhereList: [
            { c_col: "pickTaskNo", c_oper: "等于", c_value: id },
            { c_col: "storeCode", c_oper: "等于", c_value: storeCode }
        ]
    }
    const response = await bcmRequest(bcmUrl.orderApi, '拣货任务表', 'QueryPickTaskList', param);
    service.enjoyHideLoading();
    pickTaskDetail.value = response.ReturnObject[0];
    let list = []
    response.ReturnObject[0].bcmPickTaskDetailList?.map(v => {
        v.num = response.ReturnObject[0].pickTaskStatus == '1' ? 0 : v.goodsNum - v.stockoutNum;
        list.push(v)
    })
    goodsList.value = list;

}

const searchConfirm = (e) => {
    getData(e.value, StoreCode.value)
}

const scanCode = (type) => {
    uni.scanCode({
        success: function (res) {
            if (res.result != '' && res.result != undefined && res.result != null) {
                if (type != 'goods') {
                    getData(e.value, StoreCode.value)
                } else {
                    changeGdsPickNum({ value: res.result })
                }
            }
        }
    });
}

const clearSearch = (type) => {
    if (type != 'goods') {
        pickTaskNo.value = ''
        getData(BillId.value, StoreCode.value)
    } else {
        code.value = ''
    }
}

const closePickTaskGdsPopup = () => {
    // currentItem.value = null
    pickTaskGdsPopup.value.close();
}

const submit = () => {
    const { goodsBarcode, goodsCode, goodsNum, pickNum } = currentItem.value
    let index = goodsList.value.findIndex(v => v.goodsBarcode == goodsBarcode || v.goodsCode == goodsCode);
    if ((index != -1 && !!index) || (index == 0)) {
        if (goodsNum < pickNum) {
            uni.showToast({
                icon: 'none',
                title: '实拣数量不能大于应拣数量'
            })
            return
        }
        goodsList.value[index] = {
            ...goodsList.value[index],
            stockoutNum: goodsNum - pickNum,
            num: pickNum,
        }
        closePickTaskGdsPopup()
    }

}

const itemClick = (index) => {
    currentItem.value = goodsList.value[index];
    currentItem.value.pickNum = goodsList.value[index].goodsNum;
    pickTaskGdsPopup.value.open('bottom');
}

const changeGdsPickNum = (e) => {
    let goodsItem = goodsList.value.find(v => v.goodsBarcode == e.value || v.goodsCode == e.value);
    if (!!goodsItem) {
        if (pickTaskDetail.value.pickTaskStatus == '1') {
            goodsList.value.forEach(v => {
                if (v.goodsBarcode == e.value || v.goodsCode == e.value) {
                    if (v.goodsNum > v.num) {
                        v.num += 1
                        v.stockoutNum = v.goodsNum - v.num;
                    } else {
                        v.stockoutNum = 0
                    }
                }
            })
        } else {
            if (goodsItem.stockoutNum) {
                uni.navigateTo({
                    url: './goodsMergeDetail?barcode=' + goodsItem.goodsBarcode + '&storeCode=' + StoreCode.value + '&id=' + pickTaskDetail.value?.pickTaskNo
                })
            } else {
                goodsList.value.forEach(v => {
                    if (v.goodsBarcode == e.value || v.goodsCode == e.value) {
                        v.confluenceStatus = '1'
                    }
                })
            }
        }
    }
    console.log(goodsList.value, 'goodsList.valuegoodsList.value', goodsItem)
}

const pickingComplete = () => {
    uni.showModal({
        title: '提示',
        content: goodsList.value?.filter(v => !!v.stockoutNum).length ? '当前拣货任务有商品标记缺货，是否完成拣货' : '是否确认拣货任务所有商品都已完成拣货',
        success: function (res) {
            if (res.confirm) {
                pickTaskPickingComplete()
            }
        }
    })
}

const pickTaskPickingComplete = async () => {
    service.enjoyShowLoading('正在加载...')
    const param = {
        pickGoodsDetailList: [],
        pickTaskId: pickTaskDetail.value.pickTaskId,
        pickTaskNo: pickTaskDetail.value.pickTaskNo
    }
    goodsList.value?.map(v => {
        param.pickGoodsDetailList.push({
            goodsBarcode: v.goodsBarcode,
            goodsCode: v.goodsCode,
            pickNum: v.goodsNum - v.stockoutNum,
            pickTaskDetailId: v.pickTaskDetailId,
            stockoutNum: v.stockoutNum
        })
    })
    const response = await bcmRequest(bcmUrl.orderApi, '拣货任务表', 'PickTaskPickingComplete', param);
    service.enjoyHideLoading();
    uni.navigateBack()
}

const mergeComplete = () => {
    if (goodsList.value?.filter(v => !!v.stockoutNum && v.confluenceStatus == '0').length) {
        uni.showToast({
            icon: 'none',
            title: '当前拣货任务有商品标记缺货,请先标记缺货订单'
        })
        return false
    }
    uni.showModal({
        title: '提示',
        content: '是否确认已完成合流',
        success: function (res) {
            if (res.confirm) {
                pickTaskConfirmConfluence()
            }
        }
    })
}

const pickTaskConfirmConfluence = async () => {
    service.enjoyShowLoading('正在加载...')
    const param = {
        BillId: pickTaskDetail.value.pickTaskId
    }
    const response = await bcmRequest(bcmUrl.orderApi, '拣货任务表', 'PickTaskConfirmConfluence', param);
    service.enjoyHideLoading();
    uni.navigateBack()
}

onMounted(() => {
    uni.getSystemInfo({
        success: function (res) { // res - 各种参数 
            let info = uni.createSelectorQuery().select(".navigation");
            info.boundingClientRect(function (data) { //data - 各种参数
                height.value = res.windowHeight - data.height - 48 - 60 - 97;
            }).exec()
        }
    });
})

onShow(() => {
    if (BillId.value) {
        getData(BillId.value, StoreCode.value)
    }
})

onLoad(async (options) => {
    let id = options?.id, storeCode = options?.storeCode;
    BillId.value = id;
    StoreCode.value = storeCode;
    // getData(id, storeCode)
})
</script>
<style lang="scss">
@import "../common/common.css";

.content {
    padding: 0;
    background-color: #fff;
}

.content-img {
    height: 100%;
    background: #fff;
    background-repeat: no-repeat;
    background-size: 100% 150px;
}

.navigation {
    flex: 0 0 auto;
    // background: linear-gradient( 180deg, #4595F9 0%, rgba(14,219,229,0) 100%);
}

.footer {
    display: flex;
    flex-direction: column;
    flex: 1;
}

.bottom {
    display: flow-root;
    height: 70rpx;
    padding: 16rpx 40rpx;
    text-align: right;
    background: #fff;
}

.popup-content {
    display: flex;
    flex-direction: column;
    width: 100%;
    padding: 0;
    background-color: #fff;

    .popup-title {
        display: flex;
        align-items: center;
        box-sizing: border-box;
        width: 100%;
        height: 100rpx;
        padding-right: 36rpx;
        padding-left: 30rpx;
        font-size: 33rpx;
        line-height: 100rpx;
        border-bottom: 1rpx solid #f1f1f1;
    }
}

.bottom-1 {
    display: flex;
    justify-content: center;
    flex: 0 0 auto;
    height: 70rpx;
    padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
    background: $uni-bg-color;
    // border-top: 1rpx solid #979797;
}
</style>